package com.rzjm.exercise.module.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.DateUtils;
import com.rzjm.exercise.common.utils.ExcelUtils;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.common.utils.StringUtils;
import com.rzjm.exercise.module.dao.GroupsDao;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.domain.excel.FireWorkCountExcel;
import com.rzjm.exercise.module.domain.excel.FireWorkCountInfoExcel;
import com.rzjm.exercise.module.domain.excel.HighSaftyTicketExcel;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.UserService;
import org.apache.catalina.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/module/fireWork", produces = "application/json;charset=UTF-8")
public class FireWorkController extends BaseController {
    @Resource
    private FireWorkService fireWorkService;
    @Resource
    private ShopService shopService;
    @Resource
    private GroupsService groupsService;
    @Resource
    private PianqusService pianqusService;
    @Resource
    private FireWorkUserService fireWorkUserService;
    @Resource
    private DeviceWeldingRecordService weldingRecordService;
    @Resource
    private FireWorkImgService fireWorkImgService;
    @Resource
    private UserService userService;
    @Value("${projecturl.imgurl}")
    private String imgurl;

    @Log("查询作业票页面")
    @GetMapping("")
    @RequiresPermissions("module:fireWork:fireWork")
    String commonRecord(Model model) {
        UserDO user = getUser();
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 1);
        if (user.getTownId() != null && user.getTownId() > 0) {
            wrapper.eq("town_id", user.getTownId());
        }
        if (user.getGroupId() != null && user.getGroupId() > 0) {
            wrapper.eq("group_id", user.getGroupId());
        }
        List<Shop> shopList = shopService.list(wrapper);
        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() == 2) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        } else if(user.getUserType() >= 3) {//集团用户
            qw.eq("id", user.getPianquId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        model.addAttribute("ShopList",shopList);
        return "module/fireWork/list";
    }

    @Log("查询作业票页面")
    @GetMapping("/{recordType}")
    @RequiresPermissions("module:fireWork:fireWork")
    String commonRecord(Model model, @PathVariable("recordType") Integer recordType) {
        UserDO user = getUser();
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("state", 1);
        if (user.getTownId() != null && user.getTownId() > 0) {
            wrapper.eq("town_id", user.getTownId());
        }
        if (user.getGroupId() != null && user.getGroupId() > 0) {
            wrapper.eq("group_id", user.getGroupId());
        }
        List<Shop> shopList = shopService.list(wrapper);
        QueryWrapper<Pianqus> qw = new QueryWrapper<>();
        if(user.getUserType() == 2) {//集团用户
            qw.eq("jituan_id", user.getGroupId());
        } else if(user.getUserType() >= 3) {//集团用户
            qw.eq("id", user.getPianquId());
        }
        List<Pianqus> pianquses = pianqusService.list(qw);
        model.addAttribute("pianquses",pianquses);
        model.addAttribute("ShopList",shopList);
        model.addAttribute("recordType",recordType);
        return "module/fireWork/list";
    }

    @Log("查询作业票页面")
    @ResponseBody
    @GetMapping("/list")
    public DataTableLayUI<FireWork> list(DataTableLayUI<FireWork> condition) {

        UserDO userDO = getUser();
        Map<String, Object> map = condition.getSearchParams();
        QueryWrapper<FireWork> qw = new QueryWrapper<>();
        Map<String, Object> searchParams = condition.getSearchParams();
//        if (searchParams.get("timeRange") != null && StringUtils.isNotBlank(searchParams.get("timeRange").toString())) {
//            String[] timeRanges = searchParams.get("timeRange").toString().split(" - ");
//            searchParams.put("beginTime", timeRanges[0]);
//            searchParams.put("endTime", timeRanges[1]);
//            qw.between("create_time", timeRanges[0] + " 00:00:00",timeRanges[1] + " 23:59:59");
//        }

        String begin_date = map.containsKey("begin_date") ? map.get("begin_date").toString() : null;
        String end_date = map.containsKey("end_date") ? map.get("end_date").toString() : null;
        String pianquId = map.containsKey("pianquId") ? map.get("pianquId").toString() : null;

        Integer recordType = map.containsKey("recordType") && StrUtil.isNotEmpty(map.get("recordType").toString()) ?
                Integer.parseInt(map.get("recordType").toString()) : null;
        Integer workCompanyId = map.containsKey("shopId") && StrUtil.isNotEmpty(map.get("shopId").toString()) ?
                Integer.parseInt(map.get("shopId").toString()) : null;

        if(StrUtil.isNotEmpty(pianquId)){
            qw.eq("pianqu_id", pianquId);
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("create_time", begin_date + " 00:00:00",end_date + " 23:59:59");
        }

        qw.eq("record_type", recordType);

        if(userDO.getUserType() == 2){//集团管理员
            qw.eq("group_id",userDO.getGroupId());
            if(workCompanyId!= null){
                qw.eq("reg_company_id", workCompanyId);
            }
        }else if(userDO.getUserType() == 3){//片区管理员
            qw.eq("pianqu_id",userDO.getPianquId());
            if(workCompanyId!= null){
                qw.eq("reg_company_id", workCompanyId);
            }
        }else if(userDO.getUserType() == 4){//分厂管理员
            qw.eq("reg_company_id",userDO.getShopId());
        } else if(userDO.getUserType() == 10){//企业管理员
            qw.eq("reg_company_id",userDO.getShopId()).or().eq("work_company_id",userDO.getShopId());
        } else {
            if(workCompanyId!= null){
                qw.eq("reg_company_id",workCompanyId).or().eq("work_company_id",workCompanyId);
            }
        }

//        if (searchParams.get("state") != null && StringUtils.isNotBlank(searchParams.get("state").toString())) {
//            //逾期
//            if (searchParams.get("state").toString().equals("3")) {
//                searchParams.put("state","0");
//                searchParams.put("deadlineEndTime", DateUtils.getTime(new Date()));
//            }
//        }
//        condition.setSearchParams(searchParams);
        qw.orderByDesc("create_time");
        condition.setQw(qw);
        DataTableLayUI<FireWork> dt = fireWorkService.pageSearchLayUI(condition);
        return dt;
    }

    @GetMapping("/exportExcel")
    public void testExportExcel(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                @RequestParam("shopId") Integer shopId,@RequestParam("recordType") Integer recordType
            ,@RequestParam("pianquId") Integer pianquId, HttpServletResponse response){

        UserDO userDO = getUser();
        QueryWrapper<FireWork> qw = new QueryWrapper<>();
        if(userDO.getUserType() == 10){//企业人员
            qw.eq("reg_company_id",userDO.getShopId()).or().eq("work_company_id",userDO.getShopId());
        } else if(userDO.getUserType() == 2){//集团管理员
            qw.eq("group_id",userDO.getGroupId());
        }  else if(userDO.getUserType() == 3){//片区管理员
            qw.eq("pianqu_id",userDO.getPianquId());
        }  else if(userDO.getUserType() == 4 || userDO.getUserType() == 5 || userDO.getUserType() == 6 || userDO.getUserType() == 7){
            if(shopId!= null){
                qw.eq("reg_company_id",shopId).or().eq("work_company_id",shopId);
            }else{
                qw.eq("reg_company_id",userDO.getShopId()).or().eq("work_company_id",userDO.getShopId());
            }
        }

        if(recordType!= null){
            qw.eq("record_type", recordType);
        }
        if(pianquId!= null){
            qw.eq("pianqu_id", pianquId);
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
        }else{
            begin_date = DateUtils.getMonthStr(new Date()) + "-01";
            end_date = DateUtils.getDay();
            qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
        }
        qw.orderByDesc("create_time");
        List<FireWork> records = fireWorkService.list(qw);
        if (recordType == 0){
            records.forEach(record->{

                record.setFireBeginTimeStr(DateUtils.getTime(record.getFireBeginTime()) + "~" + DateUtils.getTime(record.getFireEndTime()));


                QueryWrapper<DeviceWeldingRecord> qwWelding = new QueryWrapper<>();
                qwWelding.eq("fire_work_id", record.getId());
                qwWelding.last("limit 1");
                DeviceWeldingRecord weldingRecord = weldingRecordService.getOne(qwWelding);
                if(weldingRecord != null && weldingRecord.getRebackTime()!= null){
                    //{天, 时, 分, 秒}
                    String times = DateUtils.getDistanceTimeByDate(record.getFireBeginTime(), weldingRecord.getRebackTime(),0);
                    record.setUseTimeStr(times);
                }

                QueryWrapper<FireWorkUser> qwUser = new QueryWrapper<>();
                qwUser.eq("fire_work_id", record.getId());
                List<FireWorkUser> workers = fireWorkUserService.list(qwUser);
                if(CollUtil.isNotEmpty(workers)){
                    String names = "";
                    for (FireWorkUser work : workers){
                        names += work.getWorkerName() + " ";
                    }
                    record.setWorkerNames(names);
                }

                UserDO lastCheck = userService.findById(record.getLastCheckSysUserId());
                if(lastCheck!= null){
                    record.setLastCheckUserName(lastCheck.getName());
                }


                if(record.getRecordType() == 0 || record.getRecordType() == 1){
                    if(record.getOpLevel() == 1){
                        record.setOpLevelStr("非生产类");
                    } else if(record.getOpLevel() == 2){
                        record.setOpLevelStr("生产类");
                    }
//                else{
//                    record.setOpLevelStr("特级");
//                }
                } else{
                    if(record.getOpLevel() == 1){
                        record.setOpLevelStr("非生产类");
                    } else if(record.getOpLevel() == 2){
                        record.setOpLevelStr("生产类");
                    }
//                else if(record.getOpLevel() == 3){
//                    record.setOpLevelStr("三级");
//                } else{
//                    record.setOpLevelStr("特级");
//                }
                }

                if(record.getFireType() == 0){
                    record.setFireTypeStr("电焊焊接");
                } else if(record.getFireType() == 1){
                    record.setFireTypeStr("等离子");
                } else if(record.getFireType() == 2){
                    record.setFireTypeStr("气焊(割)");
                } else if(record.getFireType() == 3){
                    record.setFireTypeStr("喷灯");
                } else if(record.getFireType() == 4){
                    record.setFireTypeStr("其他");
                }
            });
            ExcelUtils.writeExcel(response, records, FireWork.class, System.currentTimeMillis() + "_电子动火票记录.xlsx");
        }
        if (recordType == 2){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
            List<HighSaftyTicketExcel> list = new  ArrayList();
            records.forEach(record->{
                HighSaftyTicketExcel highSaftyTicketExcel = new HighSaftyTicketExcel();
                highSaftyTicketExcel.setRecordNo(record.getRecordNo());
                highSaftyTicketExcel.setApplyUser(record.getRegUserName()); //申请人
                highSaftyTicketExcel.setReqCompanyName(record.getRegCompanyName());
                highSaftyTicketExcel.setApplyTime(record.getCreateTime() == null ? "" : sdf2.format(record.getCreateTime())); //作业申请时间
                highSaftyTicketExcel.setWorkContent(record.getWorkContent()); //作业内容
                highSaftyTicketExcel.setWorkHeight(record.getWorkHeight()); //作业高度
                highSaftyTicketExcel.setWorkPosition(record.getFireAddress()); //作业地点
                List<FireWorkUser> fireWorkUsers = fireWorkUserService.selectListByColumn("fire_work_id", record.getId());
                highSaftyTicketExcel.setWorkManDept("");
                if (fireWorkUsers != null && fireWorkUsers.size() > 0) {
                    if (fireWorkUsers.get(0).getIsOut() != null && fireWorkUsers.get(0).getIsOut() == 0){
                        highSaftyTicketExcel.setWorkManDept("公司员工");
                    }else if (fireWorkUsers.get(0).getIsOut() != null && fireWorkUsers.get(0).getIsOut() == 1){
                        highSaftyTicketExcel.setWorkManDept("外协");
                    }
                    String name = fireWorkUsers.stream().map(u -> u.getWorkerName()).collect(Collectors.joining(","));
                    highSaftyTicketExcel.setWorkMan(name == null ? "" : name); //作业人
                }else {
                    highSaftyTicketExcel.setWorkMan(""); //作业人
                }
                highSaftyTicketExcel.setWorkTime((record.getFireBeginTime() == null ? "" : sdf.format(record.getFireBeginTime()))
                        + "至" + (record.getFireEndTime() == null ? "" : sdf.format(record.getFireEndTime()))); //作业实施时间
                UserDO productionManager = userService.get(record.getLastCheckSysUserId());
                highSaftyTicketExcel.setProductionManager(productionManager == null ? "" : (productionManager.getName() == null ? ""
                        : productionManager.getName()));
                UserDO safeSupervisor = userService.get(record.getSafeSysUserId());
                highSaftyTicketExcel.setSafeSupervisor(safeSupervisor == null ? ""
                        : (safeSupervisor.getName() == null ? "" : safeSupervisor.getName()));
                list.add(highSaftyTicketExcel);
            });
            ExcelUtils.writeExcel(response, list, HighSaftyTicketExcel.class, System.currentTimeMillis() + "_电子高空作业票记录.xlsx");
        }
    }

    /**
     * 动火次数导出
     *
     */
    @GetMapping("/exportWorkCount")
    public void exportWorkCount(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                @RequestParam("shopId") Integer shopId,@RequestParam("recordType") Integer recordType
            ,@RequestParam("pianquId") Integer pianquId, HttpServletResponse response){

        UserDO user = getUser();
        QueryWrapper<Pianqus> pianqusQueryWrapper = new QueryWrapper<>();
        if(user.getUserType() > 1){//集团用户
            pianqusQueryWrapper.eq("jituan_id",user.getGroupId());
        }
        if (pianquId != null){
            pianqusQueryWrapper.eq("id", pianquId);
        }
        List<Pianqus> pianquses = pianqusService.list(pianqusQueryWrapper);
        List<FireWorkCountExcel> fireWorkCountExcelList = new ArrayList<>();
        pianquses.forEach(pianqus->{
            FireWorkCountExcel fireWorkCountExcel = new FireWorkCountExcel();
            fireWorkCountExcel.setPianquName(pianqus.getPianquName());
            QueryWrapper<FireWork> qw = new QueryWrapper<>();
            if(recordType!= null){
                qw.eq("record_type", recordType);
            }
            qw.eq("pianqu_id", pianqus.getId());
            if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
            }
            Long all = fireWorkService.count(qw);
            all = all == null ? 0l : all;
            fireWorkCountExcel.setAllCount(all == null ? "0" : all.toString());
            qw.eq("state", 3);
            Long yanshou = fireWorkService.count(qw);
            yanshou = yanshou == null ? 0l : yanshou;
            fireWorkCountExcel.setCompleteCount(yanshou.toString());
            Long weiYanshou = all - yanshou;
            fireWorkCountExcel.setProgressCount(weiYanshou.toString());
            if (all > 0){
                Map<String, Object> map = new HashMap<>();
                map.put("pianquId", pianqus.getId());
                if(recordType!= null){
                    map.put("recordType", recordType);
                }
                if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                    map.put("beginTime", begin_date +" 00:00:00");
                    map.put("endTime", end_date +" 23:59:59");
                }
                Long cumulativeTime = fireWorkService.getFireWorkCumulativeTime(map);
                fireWorkCountExcel.setCumulativeTime(cumulativeTime == null ? "0" : DateUtils.getMinutesToHours(cumulativeTime));
            }else {
                fireWorkCountExcel.setCumulativeTime("0");
            }
            fireWorkCountExcelList.add(fireWorkCountExcel);
        });
        ExcelUtils.writeExcel(response, fireWorkCountExcelList, FireWorkCountExcel.class, System.currentTimeMillis() + "_动火次数统计.xlsx");
    }

    /**
     * 动火次数详细导出
     *
     */
    @GetMapping("/exportWorkCountInfo")
    public void exportWorkCountInfo(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                @RequestParam("shopId") Integer shopId,@RequestParam("recordType") Integer recordType
            ,@RequestParam("pianquId") Integer pianquId, HttpServletResponse response){

        UserDO user = getUser();
        QueryWrapper<Pianqus> pianqusQueryWrapper = new QueryWrapper<>();
        if(user.getUserType() > 1){//集团用户
            pianqusQueryWrapper.eq("jituan_id",user.getGroupId());
        }
        if (pianquId != null){
            pianqusQueryWrapper.eq("id", pianquId);
        }
        List<Pianqus> pianquses = pianqusService.list(pianqusQueryWrapper);
        List<FireWorkCountInfoExcel> fireWorkCountInfoExcelList = new ArrayList<>();
        pianquses.forEach(pianqus->{
            FireWorkCountInfoExcel fireWorkCountInfoExcel = new FireWorkCountInfoExcel();
            fireWorkCountInfoExcel.setPianquName(pianqus.getPianquName());
            // 固定动火 没有firework
            QueryWrapper<Shop> shopQueryWrapper = new QueryWrapper<>();
            shopQueryWrapper.select("id");
            shopQueryWrapper.eq("pianqu_id", pianqus.getId());
            List<Shop> shopList = shopService.list(shopQueryWrapper);
            if (shopList != null && shopList.size() > 0){
                List<Integer> shopIds = shopList.stream().map(s -> s.getId()).collect(Collectors.toList());
                QueryWrapper<DeviceWeldingRecord> gudingWrapper = new QueryWrapper<>();
                gudingWrapper.in("shop_id", shopIds);
                gudingWrapper.eq("is_safe", 1);
//                if(recordType!= null){
//                    gudingWrapper.eq("record_type", recordType);
//                }
                if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                    gudingWrapper.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
                }
                Long guidingCount = weldingRecordService.count(gudingWrapper);
                guidingCount = guidingCount == null ? 0l : guidingCount;
                fireWorkCountInfoExcel.setGudingCount(guidingCount == null ? "0" : guidingCount.toString());
                gudingWrapper.eq("state", 2);
                Long completeGudingCount = weldingRecordService.count(gudingWrapper);
                completeGudingCount = completeGudingCount == null ? 0l : completeGudingCount;
                fireWorkCountInfoExcel.setCompleteGudingCount(completeGudingCount.toString());
                Long progressGudingCount = guidingCount - completeGudingCount;
                fireWorkCountInfoExcel.setProgressGudingCount(progressGudingCount.toString());
                if (guidingCount > 0){
                    Map<String, Object> map = new HashMap<>();
                    map.put("shopIds", shopIds);
                    map.put("isSafe", 1);
//                    if(recordType!= null){
//                        map.put("recordType", recordType);
//                    }
                    if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                        map.put("beginTime", begin_date +" 00:00:00");
                        map.put("endTime", end_date +" 23:59:59");
                    }
                    Long accumulateGudingCount = weldingRecordService.getWeldingCumulativeTime(map);
                    fireWorkCountInfoExcel.setAccumulateGudingCount(accumulateGudingCount == null ? "0" : DateUtils.getMinutesToHours(accumulateGudingCount));
                }else {
                    fireWorkCountInfoExcel.setAccumulateGudingCount("0");
                }
            }else {
                fireWorkCountInfoExcel.setGudingCount("0");
                fireWorkCountInfoExcel.setProgressGudingCount("0");
                fireWorkCountInfoExcel.setAccumulateGudingCount("0");
            }

            // 生产区域动火
            QueryWrapper<FireWork> shengchanQw = new QueryWrapper<>();
            if(recordType!= null){
                shengchanQw.eq("record_type", recordType);
            }
            shengchanQw.eq("pianqu_id", pianqus.getId());
            // 动火作业级别 1 - 非生产  2 - 生产
            shengchanQw.eq("op_level",2);
            if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                shengchanQw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
            }
            Long shengchanCount = fireWorkService.count(shengchanQw);
            shengchanCount = shengchanCount == null ? 0l : shengchanCount;
            fireWorkCountInfoExcel.setShengchanCount(shengchanCount == null ? "0" : shengchanCount.toString());
            shengchanQw.eq("state", 3);
            Long completeShengchanCount = fireWorkService.count(shengchanQw);
            completeShengchanCount = completeShengchanCount == null ? 0l : completeShengchanCount;
            fireWorkCountInfoExcel.setCompleteShengchanCount(completeShengchanCount.toString());
            Long progressShengchanCount = shengchanCount - completeShengchanCount;
            fireWorkCountInfoExcel.setProgressShengchanCount(progressShengchanCount.toString());
            if (shengchanCount > 0){
                Map<String, Object> map = new HashMap<>();
                map.put("pianquId", pianqus.getId());
                map.put("opLevel", 2);
                if(recordType!= null){
                    map.put("recordType", recordType.toString());
                }
                if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                    map.put("beginTime", begin_date +" 00:00:00");
                    map.put("endTime", end_date +" 23:59:59");
                }
                Long accumulateShengchanCount = fireWorkService.getFireWorkCumulativeTime(map);
                fireWorkCountInfoExcel.setAccumulateShengchanCount(accumulateShengchanCount == null ? "0" : DateUtils.getMinutesToHours(accumulateShengchanCount));
            }else {
                fireWorkCountInfoExcel.setAccumulateShengchanCount("0");
            }
            // 非生产区域动火
            QueryWrapper<FireWork> feishengchanQw = new QueryWrapper<>();
            if(recordType!= null){
                feishengchanQw.eq("record_type", recordType.toString());
            }
            feishengchanQw.eq("pianqu_id", pianqus.getId());
            // 动火作业级别 1 - 非生产  2 - 生产
            feishengchanQw.eq("op_level",1);
            if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                feishengchanQw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
            }
            Long feishengchanCount = fireWorkService.count(feishengchanQw);
            feishengchanCount = feishengchanCount == null ? 0l : feishengchanCount;
            fireWorkCountInfoExcel.setFeichangchanCount(feishengchanCount == null ? "0" : feishengchanCount.toString());
            feishengchanQw.eq("state", 3);
            Long completeFeishengchanCount = fireWorkService.count(feishengchanQw);
            completeFeishengchanCount = completeFeishengchanCount == null ? 0l : completeFeishengchanCount;
            fireWorkCountInfoExcel.setCompleteFeishengchanCount(completeFeishengchanCount.toString());
            Long progressFeishengchanCount = feishengchanCount - completeFeishengchanCount;
            fireWorkCountInfoExcel.setProgressFeishengchanCount(progressFeishengchanCount.toString());
            if (feishengchanCount > 0){
                Map<String, Object> map = new HashMap<>();
                map.put("pianquId", pianqus.getId());
                map.put("opLevel", 1);
                if(recordType!= null){
                    map.put("recordType", recordType.toString());
                }
                if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
                    map.put("beginTime", begin_date +" 00:00:00");
                    map.put("endTime", end_date +" 23:59:59");
                }
                Long accumulateFeishengchanCount = fireWorkService.getFireWorkCumulativeTime(map);
                fireWorkCountInfoExcel.setAccumulateFeishengchanCount(accumulateFeishengchanCount == null ? "0" : DateUtils.getMinutesToHours(accumulateFeishengchanCount));
            }else {
                fireWorkCountInfoExcel.setAccumulateFeishengchanCount("0");
            }

            fireWorkCountInfoExcelList.add(fireWorkCountInfoExcel);
        });
        ExcelUtils.writeExcel(response, fireWorkCountInfoExcelList, FireWorkCountInfoExcel.class, System.currentTimeMillis() + "_焊机动火次数和时长统计.xlsx");
    }

    @Log("编辑作业票页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:fireWork:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        FireWork fireWork = fireWorkService.findById(id);
        model.addAttribute("fireWork", fireWork);
        return "module/fireWork/detail";
    }


    @Log("更新作业票")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:fireWork:edit")
    public R update(@Valid FireWork fireWork) {
        UserDO user = getUser();
        fireWork.setState(1);
        fireWorkService.updateById(fireWork);
        return R.ok();
    }

    @Log("删除作业票")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("module:fireWork:remove")
    public R remove(Integer id) {
        if (fireWorkService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }



    @RequiresPermissions("module:fireWork:batchRemove")
    @Log("批量删除")
    @PostMapping("/batchRemove")
    @ResponseBody
    R batchRemove(@RequestParam("ids[]") Integer[] ids) {
        List<Integer> idList = Arrays.asList(ids);
        if (fireWorkService.removeByIds(idList)) {
            return R.ok();
        }
        return R.error();
    }

    @Log("作业详情票页面")
    @GetMapping("/detail/{id}")
    String detail(@PathVariable("id") Integer id, Model model) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        FireWork fireWork = fireWorkService.findById(id);
        if (fireWork != null && fireWork.getRecordType() == 0){
            Groups groups = groupsService.findById(fireWork.getGroupId());
            fireWork.setGroupName(groups == null ? "" : groups.getGroupName());
            Pianqus pianqus = pianqusService.getById(fireWork.getPianquId());
            fireWork.setPianquName(pianqus == null ? "" : pianqus.getPianquName());
            String workLevel = "";
            if (fireWork.getOpLevel() == null) {
                workLevel = "";
            } else if (fireWork.getOpLevel() == 1) {
                workLevel = "非生产区域动火";
            } else if (fireWork.getOpLevel() == 2) {
                workLevel = "生产区域动火";
            }
            fireWork.setOpLevelStr(workLevel);
            String workWay = "";
            if (fireWork.getFireType() == null) {
                workWay = "";
            } else if (fireWork.getFireType() == 0) {
                workWay = "电焊";
            } else if (fireWork.getFireType() == 2) {
                workWay = "气焊(割)";
            } else if (fireWork.getFireType() == 1) {
                workWay = "等离子";
            } else if (fireWork.getFireType() == 3) {
                workWay = "喷灯";
            } else if (fireWork.getFireType() == 4) {
                workWay = "其他";
            }
            fireWork.setFireTypeStr(workWay); //动火方式
            fireWork.setWorkEffectiveTime((fireWork.getFireBeginTime() == null ? "" : sdf.format(fireWork.getFireBeginTime()) + "至")
                    + (fireWork.getFireEndTime() == null ? "" : sdf.format(fireWork.getFireEndTime()) + "止")); //动火作业实施时间
            String workMan = "";
            String certificateNo = "";
            FireWorkUser fireWorkUser = fireWorkUserService.selectByUniqueColumn("fire_work_id", fireWork.getId());
            if (fireWorkUser != null) {
                workMan = (fireWorkUser.getWorkerName() == null ? "" : fireWorkUser.getWorkerName());
                certificateNo = (fireWorkUser.getWorkCardNum() == null ? "" : fireWorkUser.getWorkCardNum());
            }
            fireWork.setWorkMan(workMan);
            fireWork.setCertificateNo(certificateNo);
            List<FireWorkImg> list = fireWorkImgService.selectListByColumn("fire_work_id", id);
            List<String> examineImgList = list.stream().filter(img -> img.getImgType() == 0).map(img -> imgurl + img.getImgUrl()).collect(Collectors.toList());
            List<String> acceptImgList = list.stream().filter(img -> img.getImgType() == 1).map(img -> imgurl + img.getImgUrl()).collect(Collectors.toList());



            fireWork.setExamineImgList(examineImgList);
            fireWork.setAcceptImgList(acceptImgList);


            fireWork.setApplyTime(fireWork.getCreateTime() == null ? "" : sdf.format(fireWork.getCreateTime()));

            fireWork.setApproverTime(fireWork.getLastSubmitTime() == null ? "" : sdf.format(fireWork.getLastSubmitTime()));
            fireWork.setExaminerTime(fireWork.getLastCheckTime() == null ? "" : sdf.format(fireWork.getLastCheckTime()));
            UserDO examiner = userService.get(fireWork.getLastCheckSysUserId());
            fireWork.setExaminer(examiner == null ? "" : (examiner.getName() == null ? "" : examiner.getName()));

            if (StringUtils.isNotEmpty(fireWork.getExaminerTime())){
                fireWork.setExaminerOpinion(fireWork.getLastCheckState() == null ? ""
                        : (fireWork.getLastCheckState() == 1 ? "同意" : fireWork.getLastCheckState() == 0 ? "不同意" : "")); //审核人意见

            }
            UserDO approver = userService.get(fireWork.getLastSubmitSysUserId());
            fireWork.setApprover(approver == null ? "" : (approver.getName() == null ? "" : approver.getName()));
            if (StringUtils.isNotEmpty(fireWork.getApproverTime())){
                fireWork.setApproverOpinion(fireWork.getLastSubmitState() == null ? ""
                        : (fireWork.getLastSubmitState() == 1 ? "同意" : fireWork.getLastSubmitState() == 0 ? "不同意" : "")); //批准人意见

            }
            fireWork.setAcceptTime(fireWork.getCheckAcceptTime() == null ? "" : sdf.format(fireWork.getCheckAcceptTime()));
//            if (StringUtils.isNotEmpty(fireWork.getAcceptTime())){
                UserDO acceptPerson = userService.get(fireWork.getCheckAcceptSysUserId());
                fireWork.setAcceptPerson(acceptPerson == null ? "" : (acceptPerson.getName() == null ? "" : acceptPerson.getName()));
//            }

        }else if (fireWork != null && (fireWork.getRecordType() == 2 || fireWork.getRecordType() == 1)) {
            fireWork.setApplyTime(fireWork.getCreateTime() == null ? "" : sdf.format(fireWork.getCreateTime()));
            fireWork.setWorkEffectiveTime((fireWork.getFireBeginTime() == null ? "" : sdf.format(fireWork.getFireBeginTime()) + "~")
                    + (fireWork.getFireEndTime() == null ? "" : sdf.format(fireWork.getFireEndTime())));
            String workMan = "";
            String workManType = "";
            List<FireWorkUser> fireWorkUsers = fireWorkUserService.selectListByColumn("fire_work_id", fireWork.getId());
//            FireWorkUser fireWorkUser = fireWorkUserService.selectByUniqueColumn("fire_work_id", fireWork.getId());
            if (fireWorkUsers != null && fireWorkUsers.size() > 0) {
                if (fireWorkUsers.get(0).getIsOut() != null && fireWorkUsers.get(0).getIsOut() == 0){
                    workManType = "公司员工";
                }else if (fireWorkUsers.get(0).getIsOut() != null && fireWorkUsers.get(0).getIsOut() == 1){
                    workManType = "外协";
                }
                workMan = fireWorkUsers.stream().map(u -> u.getWorkerName()).collect(Collectors.joining(","));
//                workManType = fireWorkUsers.stream().map(u -> u.getIsOut() == 0 ? "公司员工" : "外协").collect(Collectors.joining(","));
//                workMan = (fireWorkUser.getWorkerName() == null ? "" : fireWorkUser.getWorkerName());
            }
            fireWork.setWorkMan(workMan);
            fireWork.setWorkManType(workManType);
            fireWork.setProductionManagerSignTime(fireWork.getLastCheckTime() == null ? "" : sdf.format(fireWork.getLastCheckTime()));
            fireWork.setSafeSupervisorTime(fireWork.getSafeOpTime() == null ? "" : sdf.format(fireWork.getSafeOpTime()));
            fireWork.setAcceptTime(fireWork.getCheckAcceptTime() == null ? "" : sdf.format(fireWork.getCheckAcceptTime()));

//            if (StringUtils.isNotEmpty(fireWork.getProductionManagerSignTime())){
                UserDO productionManager = userService.get(fireWork.getLastCheckSysUserId());
                fireWork.setProductionManager(productionManager == null ? "" : (productionManager.getName() == null ? ""
                        : productionManager.getName()));
//            }
//            if (StringUtils.isNotEmpty(fireWork.getSafeSupervisorTime())){
                UserDO safeSupervisor = userService.get(fireWork.getSafeSysUserId());
                fireWork.setSafeSupervisor(safeSupervisor == null ? ""
                        : (safeSupervisor.getName() == null ? "" : safeSupervisor.getName()));
//            }
//            if (StringUtils.isNotEmpty(fireWork.getAcceptTime())){
                UserDO acceptPerson = userService.get(fireWork.getCheckAcceptSysUserId());
                fireWork.setAcceptPerson(acceptPerson == null ? "" : (acceptPerson.getName() == null ? "" : acceptPerson.getName()));
//            }
//            fireWork.setSafeSupervisorOpinion(fireWork.getSafeOpState() == null ? ""
//                    : (fireWork.getSafeOpState() == 1 ? "同意" : fireWork.getSafeOpState() == 0 ? "不同意" : ""));
//            fireWork.setProductionManagerOpinion(fireWork.getLastCheckState() == null ? ""
//                    : (fireWork.getLastCheckState() == 1 ? "同意" : fireWork.getLastCheckState() == 0 ? "不同意" : ""));

        }
        model.addAttribute("fireWork", fireWork);
        return "module/fireWork/detail";
    }
}
